package com.zx._08_网络.cpt3_udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class Server {

    //定义服务器端口
    public static final int PORT = 30000;
    //定义每个数据报的大小为4KB
    private static final int DATA_LEN = 4096;
    //指定接受数据报的字节数组
    byte[] inBuff = new byte[DATA_LEN];
    String[] books = {"aaa", "bbb", "ccc", "ddd"};
    //定义一个用于接收数据报的DatagramPacket对象，   设置它的数据报的字节数组和大小
    private DatagramPacket inPacket = new DatagramPacket(inBuff, inBuff.length);
    //定义一个用于发送数据报的DatagramPacket
    private DatagramPacket outPacket;

    public static void main(String[] args) throws IOException {
        System.out.println("Server");
        new Server().init();
    }

    public void init() throws IOException {
        //创建一个DatagramSocket对象
        DatagramSocket socket = new DatagramSocket(PORT);
        for (int i = 0; i < 1000; i++) {
            //读取socket中的数据，读取的数据保存到inPacket中
            socket.receive(this.inPacket);
            //判断他两是否是同一个数组
            //System.out.println(this.inBuff == this.inPacket.getData());
            //将接收到的数据报转化为字符串
            System.out.println(new String(inBuff, 0, inPacket.getLength()));
            //取出一个元素作为发送的内容
            byte[] sendData = books[i % 4].getBytes();
            //以刚接到的DatagramSocket的原SocketAddress作为发送目标
            this.outPacket = new DatagramPacket(sendData, sendData.length, this.inPacket.getSocketAddress());
            socket.send(outPacket);
        }
    }
}
